import {
  ArgumentsHost,
  Catch,
  ExceptionFilter,
  HttpException,
} from '@nestjs/common';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const res = ctx.getResponse();
    const status = exception.getStatus();
    const message =
      exception.message ??
      `${status >= 500 ? 'Service Error' : 'Client Error'}`;
    const errorRes = {
      data: {},
      message: message,
      code: -1,
    };
    res.status(status);
    res.header('Content-Type', 'application/json; charset=utf-8'); // charset-utf-8 错一个字符导致无法reject
    res.send(errorRes);
  }
}
